<template>
  <a-modal
    title="字段设置"
    v-model="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :width="750"
    okText="确定"
    cancelText="取消"
  >
    <Button type="primary" style="margin-bottom: 10px" @click="addField"
      >新增字段</Button
    >
    <Table
      :columns="columns"
      :data-source="data"
      :rowKey="returnRowKey"
      size="small"
      :pagination="false"
    >
      <template slot="fieldName" slot-scope="text, record, index">
        <Input
          :defaultValue="text"
          @change="(e) => handleChange('fieldName', e.target.value, index)"
        />
      </template>
      <template slot="field" slot-scope="text, record, index">
        <Input
          :defaultValue="text"
          @change="(e) => handleChange('field', e.target.value, index)"
        />
      </template>

      <template slot="action" slot-scope="text, record">
        <Button type="link" @click="deleteField(record.id)">删除</Button>
      </template>
    </Table>
  </a-modal>
</template>

<script>
import Button from "ant-design-vue/lib/button/button";
import Input from "ant-design-vue/lib/input";
import Table from "ant-design-vue/lib/table";

const columns = [
  {
    title: "排序",
    width: "10%",
    customRender: function (t, r, i) {
      return i + 1;
    },
  },
  {
    title: "字段名称",
    dataIndex: "fieldName",
    width: "40%",
    scopedSlots: { customRender: "fieldName" },
  },
  {
    title: "字段",
    dataIndex: "field",
    width: "40%",
    scopedSlots: { customRender: "field" },
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
    width: "10%",
    scopedSlots: { customRender: "action" },
  },
];
function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
}
export default {
  components: {
    Button,
    Input,
    Table,
  },
  props: {},
  data() {
    return {
      visible: false,
      columns,
      data: [this.getEmptyTableItem()],
    };
  },
  methods: {
    showModal() {
      this.visible = true;
    },
    returnRowKey(record) {
      return record.id;
    },
    getEmptyTableItem() {
      let id = guid();
      return {
        fieldName: "",
        field: "",
        id,
      };
    },

    addField() {
      this.data.push(this.getEmptyTableItem());
    },
    deleteField(id) {
      let copyData = [...this.data];
      this.data = copyData.filter((item) => id !== item.id);
    },
    handleChange(key, value, index) {
      let actionObj = this.data[index];
      actionObj[key] = value;
    },
    handleOk() {},
    handleCancel() {
      this.visible = false;
      this.$emit("onClose");
    },
  },
};
</script>

<style lang="css" scoped>
</style>